package com.example.springbootdemo.entity

import com.example.springbootdemo.defination.CommontInfo
import com.fasterxml.jackson.annotation.JsonAlias
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import org.hibernate.annotations.GenericGenerator
import org.hibernate.engine.spi.SharedSessionContractImplementor
import org.hibernate.id.IncrementGenerator
import org.springframework.beans.factory.annotation.Value
import java.io.Serializable
import javax.persistence.*

@Entity
data class Person(
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO, generator = "custom-increment")
        @GenericGenerator(name = "custom-increment", strategy = "com.example.springbootdemo.entity.PersonIDGenerator")
        val id: Long = 0L,
        var name: String
) {
    @JsonIgnore
    @ManyToOne(cascade = [CascadeType.ALL], targetEntity = Department::class)
    var department: Department? = null


    @Transient
    var department_url: String? = null
        @JsonProperty("department")
        get() = department?.let { "${CommontInfo.host}/departments/${it.id}" }
}


class PersonIDGenerator : IncrementGenerator() {
    override fun generate(session: SharedSessionContractImplementor?, `object`: Any?): Serializable {
        val id: Long = (`object` as Person).id
        return if (id != 0L) id
        else super.generate(session, `object`)
    }
}